<template>
  <el-form
    ref="formInstance"
    :model="values"
    label-width="60px"
    class="demo-ruleForm"
    status-icon
  >
    <el-form-item label="Alt" prop="alt">
      <el-input v-model="values.alt" style="width: 200px" />
    </el-form-item>
    <el-form-item label="Link" prop="link">
      <el-input v-model="values.link" style="width: 200px" />
    </el-form-item>
    <el-form-item label="上传图片">
      <input type="file" ref="uploadInp" @change="handleFileChange" />
    </el-form-item>
    <el-form-item>
      <img width="200" :src="values.img" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { postBannerItemApi } from '@/api/banner'
export default {
  name: 'AppBannerCreate',
  data () {
    return {
      values: {
        link: '',
        alt: '',
        img: ''
      }
    }
  },
  methods: {
    handleFileChange (e) {
      const file = e.target.files[0]
      // 读取文件的内容, 需要创建一个file-reader实例
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        this.values.img = e.target.result
      }
    },
    async handleSubmit () {
      console.log(this.values);
      if (!this.values.img) {
        this.$message({ type: 'error', message: '请上传图片后操作' })
      } else {
        try {
          await postBannerItemApi(this.values)
          this.$router.push({ name: 'banner-swiper' })
        } catch (error) {}
      }
    }
  }
}
</script>
